﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Data.Common;

namespace SP.OpenSource.CDC.Monitor.BLL
{
    class Monitor
    {
        public static bool GetErrorLog(String sConnection, ref DataTable dtOutErrorLog, ref String sErrorMessage)
        {
            try
            {   
                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = sConnection;

                DbCommand command = factory.CreateCommand();

                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                String sQuery = "select session_id as SessionID, phase_number as PhaseNumber,";
                sQuery += " entry_time as EntryTime, [error_number] as ErrorNumber, ";
                sQuery += " [error_severity]  as ErrorSeverity, [error_state] as ErrorState, ";
                sQuery += " [error_message] as ErrorMessage, start_lsn as StartLSN, begin_lsn as BeginLSN, sequence_value as SequenceValue ";
                sQuery += " from sys.dm_cdc_errors ";
                 
                /* //Testing
                 * sQuery = "select 'session_id' as SessionID, 'phase_number' as PhaseNumber,";
                sQuery += " 'entry_time' as EntryTime, '[error_number]' as ErrorNumber, ";
                sQuery += " '[error_severity]'  as ErrorSeverity, '[error_state]' as ErrorState, ";
                sQuery += " '[error_message]' as ErrorMessage, 'start_lsn' as StartLSN, 'begin_lsn' as BeginLSN, 'sequence_value' as SequenceValue ";
                */

                command.Connection = connection;
                command.CommandType = CommandType.Text;
                command.CommandText = sQuery;

                DbDataAdapter adapter = factory.CreateDataAdapter();
                adapter.SelectCommand = command;
                adapter.Fill(dtOutErrorLog);

                return true;
            }
            catch (Exception ex)
            {
                sErrorMessage = ex.Message;
                return false;
            }
        }
    }
}
